<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-22
 * Time: 18:50
 * 退款操作
 */

namespace app\api\service;


use app\api\model\GoodsOrder;
use app\api\model\HotelRoomOrder;
use app\lib\exception\ParameterException;

class AdminWxRefund extends Token
{
    /**
     * 1.判断用户信息
     * 2.判断订单信息
     * 3.判断订单时间 得出退款金额进行退款操作
     */
    // 用户ID
    private $postArr;

    // 订单信息
    private $order;

    // 退款金额
    private $price;

    function __construct($postArr)
    {
        $this->postArr = $postArr;
        $this->order = GoodsOrder::get($this->postArr['order_id']);
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeOrder();
    }

    // 判断订单
    private function judgeOrder()
    {
        if($this->postArr['string'] != 'N#l0owmG82aDGxH') {
            throw new ParameterException([
                'msg' => [
                    'room_order' => '订单不存在'
                ]
            ]);
        }
        if($this->order['status'] != 5) {
            throw new ParameterException([
                'msg' => [
                    'room_order' => '订单状态错误'
                ]
            ]);
        }
        return $this->judgeData();
    }

    // 判断时间并得出退款金额
    private function judgeData()
    {
        $this->price = $this->order['price'];
        if($this->price == 0) {
           $this->changeStatus();
            return writeJson(201, [], '退款成功！');
        } else {
           return $this->orderRefund();
        }
    }

    // 进行退款操作
    private function orderRefund()
    {
        $wxOrderData = new \WxPayRefund();
        $wxOrderData->SetOut_trade_no($this->order['out_trade_no']);
        $wxOrderData->SetOut_refund_no($this->order['out_refund_no']);
        $wxOrderData->SetTotal_fee((int)(round($this->price,2)*100));
        $wxOrderData->SetRefund_fee((int)(round($this->price,2)*100));
        $wxOrderData->SetOp_user_id(config('wx.op_user_id'));
        $config = new \WxPayConfig();
        $order_info = \WxPayApi::refund($config, $wxOrderData);
        if ($order_info['return_code'] == 'SUCCESS' && $order_info['result_code'] == 'SUCCESS') {
            $this->changeStatus();
            return writeJson(202, [], '退款成功！');
        } else {
            throw new ParameterException([
                'msg' => [
                    'goods_order' => $order_info['err_code_des']
                ]
            ]);
        }
    }

    // 修改状态
    private function changeStatus()
    {
        GoodsOrder::where('id',$this->order['id'])->update([
            'admin_refund_time' => time(),
            'status' => 6,
        ]);
    }

}